package cn.tedu.search.config;

import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

@Configuration
@ConfigurationProperties("es")
@Data
public class ESConfig {
    List<String> nodes;

    /**
     * 超时时间 5分钟
     */
    static final int TIME_OUT = 5 * 60 * 1000;
    static final int ADDRESS_LENGTH = 2;
    static final String HTTP_SCHEME = "http";

    private HttpHost makeHttpHost(String s) {
        assert StringUtils.isNotEmpty(s);
        String[] address = s.split(":");
        if (address.length == ADDRESS_LENGTH) {
            String ip = address[0];
            int port = Integer.parseInt(address[1]);
            System.err.println(ip + "+" + port);
            return new HttpHost(ip, port, HTTP_SCHEME);
        } else {
            return null;
        }
    }

    @Bean
    public RestClientBuilder restClientBuilder() {
        HttpHost[] httpHosts = new HttpHost[nodes.size()];
        int index = 0;
        for (String node : nodes) {
            String[] strs = node.split(":");
            String ip = strs[0];
            Integer port = Integer.parseInt(strs[1]);
            httpHosts[index++] = new HttpHost(ip, port);
        }
        return RestClient.builder(httpHosts);
    }

    @Bean(name = "highLevelClient")
    public RestHighLevelClient highLevelClient(@Autowired RestClientBuilder restClientBuilder) {
        restClientBuilder.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
            @Override
            public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) {
                return requestConfigBuilder.setSocketTimeout(TIME_OUT);
            }
        });
        return new RestHighLevelClient(restClientBuilder);
    }
}
